
##Adapted qwraps2::mean_sd function to include weights and automatically remove NAs using SDMTools package

library(qwraps2)
library(SDMTools)

wmean_sd <- function(x, w, 
                    digits = getOption("qwraps2_frmt_digits", 2), 
                    na_rm = FALSE, 
                    show_n = "ifNA", 
                    denote_sd = "pm", 
                    markup = getOption("qwraps2_markup", "latex")) { 
  n <- sum(!is.na(x))
  m <- wt.mean(x, w) # changed to wt.mean from SDMTools package
  s <- wt.sd(x, w) # changed to wt.sd from SDMTools package

  if (all(!(show_n %in% c("ifNA", "always", "never")))) { 
    warning("'show_n' should be in c('ifNA', 'always', 'never').  Setting to 'ifNA'.")
    show_n <- "ifNA"
  }
  
  if (show_n == "always" | (show_n == "ifNA" & any(is.na(x)))) { 
    rtn <- paste0(frmt(as.integer(n), digits), "; ", frmt(m, digits), " $\\pm$ ", frmt(s, digits))
  } else { 
    rtn <- paste0(frmt(m, digits), " $\\pm$ ", frmt(s, digits))
  }
  
  if (denote_sd == "paren") { 
    rtn <- gsub("\\$\\\\pm\\$\\s(.*)", "\\(\\1\\)", rtn)
  }
  
  if (markup == "markdown") { 
    rtn <- gsub("\\$\\\\pm\\$", "&plusmn;", rtn)
  }
  
  return(rtn)
}
